import { ref, computed } from 'vue'
import { supabase } from '../lib/supabase'
import type { 
  MessageWithDetails, 
  MessageSettings, 
  CreateMessageParams, 
  UpdateMessageSettingsParams,
  MessageResponse 
} from '../types/messages'

// 模块级单例状态，确保全局共享，避免多个组件各自维护导致不同步
const messages = ref<MessageWithDetails[]>([])
const messageSettings = ref<MessageSettings | null>(null)
const unreadCount = ref(0)
const loading = ref(false)
const error = ref<string | null>(null)
const hasMore = ref(true)
const currentPage = ref(0)
const pageSize = 20

// 初始化与订阅去重控制
let initialized = false
let unsubscribeRealtime: null | (() => void) = null

// 计算属性
const unreadMessages = computed(() =>
  messages.value.filter(msg => !msg.is_read)
)

const readMessages = computed(() =>
  messages.value.filter(msg => msg.is_read)
)

// 获取消息列表
const loadMessages = async (unreadOnly = false, reset = false) => {
  if (loading.value) return

  loading.value = true
  error.value = null

  try {
    if (reset) {
      currentPage.value = 0
      messages.value = []
      hasMore.value = true
    }

    const { data, error: dbError } = await supabase.rpc('get_user_messages', {
      p_limit: pageSize,
      p_offset: currentPage.value * pageSize,
      p_unread_only: unreadOnly
    })

    if (dbError) throw dbError

    if (data) {
      const newMessages = data.map((msg: any) => ({
        id: msg.message_id,
        recipient_id: '', // 当前用户
        sender_id: msg.sender_id,
        type: msg.type,
        title: msg.title,
        content: msg.content,
        related_movie_id: msg.related_movie_id,
        related_movie_title: msg.related_movie_title,
        related_comment_id: msg.related_comment_id,
        is_read: msg.is_read,
        created_at: msg.created_at,
        updated_at: msg.created_at, // 使用created_at作为updated_at
        sender_name: msg.sender_name,
        sender_avatar: msg.sender_avatar,
        sender_is_ai: msg.sender_is_ai
      }))

      if (reset) {
        messages.value = newMessages
      } else {
        messages.value.push(...newMessages)
      }

      hasMore.value = newMessages.length === pageSize
      currentPage.value++
    }
  } catch (err) {
    console.error('Error loading messages:', err)
    error.value = err instanceof Error ? err.message : '加载消息失败'
  } finally {
    loading.value = false
  }
}

// 加载更多消息
const loadMore = async (unreadOnly = false) => {
  if (hasMore.value && !loading.value) {
    await loadMessages(unreadOnly, false)
  }
}

// 标记消息为已读
const markAsRead = async (messageId: number): Promise<MessageResponse> => {
  try {
    const { data, error: dbError } = await supabase.rpc('mark_message_as_read', {
      p_message_id: messageId
    })

    if (dbError) throw dbError

    if (data?.success) {
      // 更新本地状态
      const message = messages.value.find(msg => msg.id === messageId)
      if (message) {
        message.is_read = true
      }
      
      // 更新未读数量
      await updateUnreadCount()
      
      return { success: true, message: data.message }
    } else {
      return { success: false, error: data?.error || '标记失败' }
    }
  } catch (err) {
    console.error('Error marking message as read:', err)
    return { 
      success: false, 
      error: err instanceof Error ? err.message : '标记失败' 
    }
  }
}

// 标记所有消息为已读
const markAllAsRead = async (): Promise<MessageResponse> => {
  try {
    const { data, error: dbError } = await supabase.rpc('mark_all_messages_as_read')

    if (dbError) throw dbError

    if (data?.success) {
      // 更新本地状态
      messages.value.forEach(msg => {
        msg.is_read = true
      })
      
      // 更新未读数量
      unreadCount.value = 0
      
      return { success: true, message: data.message }
    } else {
      return { success: false, error: data?.error || '标记失败' }
    }
  } catch (err) {
    console.error('Error marking all messages as read:', err)
    return { 
      success: false, 
      error: err instanceof Error ? err.message : '标记失败' 
    }
  }
}

// 删除消息
const deleteMessage = async (messageId: number): Promise<MessageResponse> => {
  try {
    const { data, error: dbError } = await supabase.rpc('delete_message', {
      p_message_id: messageId
    })

    if (dbError) throw dbError

    if (data?.success) {
      // 从本地状态中移除
      const index = messages.value.findIndex(msg => msg.id === messageId)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
      
      // 更新未读数量
      await updateUnreadCount()
      
      return { success: true, message: data.message }
    } else {
      return { success: false, error: data?.error || '删除失败' }
    }
  } catch (err) {
    console.error('Error deleting message:', err)
    return { 
      success: false, 
      error: err instanceof Error ? err.message : '删除失败' 
    }
  }
}

// 获取未读消息数量
const updateUnreadCount = async () => {
  try {
    const { data, error: dbError } = await supabase.rpc('get_unread_message_count')

    if (dbError) throw dbError

    unreadCount.value = data || 0
  } catch (err) {
    console.error('Error getting unread count:', err)
    // 如果获取失败，使用本地计算
    unreadCount.value = unreadMessages.value.length
  }
}

// 获取消息设置
const loadMessageSettings = async () => {
  try {
    const { data, error: dbError } = await supabase
      .from('message_settings')
      .select('*')
      .single()

    if (dbError && dbError.code !== 'PGRST116') { // PGRST116 = no rows returned
      throw dbError
    }

    messageSettings.value = data
  } catch (err) {
    console.error('Error loading message settings:', err)
    error.value = err instanceof Error ? err.message : '加载设置失败'
  }
}

// 更新消息设置
const updateMessageSettings = async (settings: UpdateMessageSettingsParams): Promise<MessageResponse> => {
  try {
    const { data, error: dbError } = await supabase.rpc('update_message_settings', {
      p_comment_replies: settings.comment_replies,
      p_movie_uploads: settings.movie_uploads,
      p_system_notifications: settings.system_notifications,
      p_likes: settings.likes,
      p_follows: settings.follows,
      p_email_notifications: settings.email_notifications
    })

    if (dbError) throw dbError

    if (data?.success) {
      // 重新加载设置
      await loadMessageSettings()
      return { success: true, message: data.message }
    } else {
      return { success: false, error: data?.error || '更新失败' }
    }
  } catch (err) {
    console.error('Error updating message settings:', err)
    return { 
      success: false, 
      error: err instanceof Error ? err.message : '更新失败' 
    }
  }
}

// 创建消息（用于测试或手动发送）
const createMessage = async (params: CreateMessageParams): Promise<MessageResponse> => {
  try {
    const { data, error: dbError } = await supabase.rpc('create_message', {
      p_recipient_id: params.recipient_id,
      p_sender_id: params.sender_id || null,
      p_type: params.type,
      p_title: params.title,
      p_content: params.content,
      p_related_movie_id: params.related_movie_id,
      p_related_comment_id: params.related_comment_id
    })

    if (dbError) throw dbError

    if (data?.success) {
      // 更新未读数量
      await updateUnreadCount()
      return { success: true, message: data.message, data: data.message_id }
    } else {
      return { success: false, error: data?.error || '发送失败' }
    }
  } catch (err) {
    console.error('Error creating message:', err)
    return { 
      success: false, 
      error: err instanceof Error ? err.message : '发送失败' 
    }
  }
}

// 初始化（幂等）
const init = async () => {
  // 只有在已登录情况下才进行初始化，避免未登录时把 initialized 置为 true
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return

  if (initialized) return
  try {
    await Promise.all([
      loadMessages(false, true),
      loadMessageSettings(),
      updateUnreadCount()
    ])

    // 设置实时监听（只订阅一次）
    await setupRealtimeListener()
    initialized = true
  } catch (e) {
    console.error('useMessages: 初始化失败:', e)
    throw e
  }
}
  
// 设置实时监听（只注册一次）
const setupRealtimeListener = async () => {
  if (unsubscribeRealtime) return

  const { data: { user } } = await supabase.auth.getUser()
  if (!user) {
    return
  }

  const channel = supabase
    .channel(`messages_changes_${user.id}`)
    .on(
      'postgres_changes',
      {
        event: '*',
        schema: 'public',
        table: 'messages',
        filter: `recipient_id=eq.${user.id}`
      },
      async (payload) => {
        if (payload.eventType === 'INSERT' || payload.eventType === 'UPDATE') {
          await updateUnreadCount()
          if (payload.eventType === 'INSERT') {
            await loadMessages(false, true)
          }
        }
      }
    )
    .subscribe()

  unsubscribeRealtime = () => {
    supabase.removeChannel(channel)
    unsubscribeRealtime = null
  }
}

// 加载最近消息（用于下拉菜单）
const loadRecentMessages = async () => {
  await loadMessages(false, true)
}

// 清理（可用于登出时）
const clearMessages = () => {
  messages.value = []
  messageSettings.value = null
  unreadCount.value = 0
  error.value = null
  hasMore.value = true
  currentPage.value = 0
  initialized = false
  if (unsubscribeRealtime) {
    unsubscribeRealtime()
  }
}

export function useMessages() {

  return {
    // 状态
    messages,
    messageSettings,
    unreadCount,
    loading,
    error,
    hasMore,
    
    // 计算属性
    unreadMessages,
    readMessages,
    
    // 方法
    loadMessages,
    loadMore,
    markAsRead,
    markAllAsRead,
    deleteMessage,
    updateUnreadCount,
    loadMessageSettings,
    updateMessageSettings,
    createMessage,
    init,
    loadRecentMessages,
    clearMessages
  }
}
